package com.hnhuas.salary.common.utils;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


public class XlsxReaderUtil extends DefaultHandler {
    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(XlsxReaderUtil.class);
    // 共享字符串表
    private SharedStringsTable sst;
    // 上一次的内容
    private String lastContents;
    private boolean nextIsString;
    private boolean cellNull;
    private int sheetIndex = -1;
    private List<String> rowlist = new ArrayList<String>();
    // 当前行
    private int curRow = 0;
    // 当前列
    private int curCol = 0;

    private int totalRow = 0;
    //用来控制解析多少行
    private int controlParseNum = 0;
    //用来标识已经中断解析
    private boolean terminateParseFlag = false;
    //源表头
    private List<String> title = new ArrayList<String>();
    //源表数据
    private List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    //源文件中缺少字段信息的无效数据信息记录
    private List<String> errorList = new ArrayList<String>();
    private String path;

    public XlsxReaderUtil() {
        super();
    }

    public XlsxReaderUtil(String path, int controlParseNum) {
        super();
        this.path = path;
        this.controlParseNum = controlParseNum;
    }

    /**
     * 只遍历一个电子表格，其中sheetId为要遍历的sheet索引，从1开始，1-3
     * @param filename
     * @param sheetId
     * @throws Exception
     */
    public void processOneSheet(String filename, int sheetId) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);

        // 根据 rId# 或 rSheet# 查找sheet
        InputStream sheet2 = r.getSheet("rId" + sheetId);
        sheetIndex++;
        InputSource sheetSource = new InputSource(sheet2);
        parser.parse(sheetSource);
        sheet2.close();
    }

    /**
     * 遍历工作簿中所有的电子表格
     * @throws Exception
     */
    public List<Map<String, Object>> process() {
        List<Map<String, Object>> maps = new ArrayList<>();
        //System.out.println(System.currentTimeMillis());
        XMLReader parser = null;
        Iterator<InputStream> sheets = null;
        try {
            OPCPackage pkg = OPCPackage.open(path);
            XSSFReader r = new XSSFReader(pkg);
            SharedStringsTable sst = r.getSharedStringsTable();
            parser = fetchSheetParser(sst);
            sheets = r.getSheetsData();
        } catch (InvalidFormatException e) {
            LOGGER.error("process() InvalidFormat error", e);
        } catch (IOException e) {
            LOGGER.error("process() IO error", e);
        } catch (OpenXML4JException e) {
            LOGGER.error("process() OpenXML4J error", e);
        } catch (SAXException e) {
            LOGGER.error("process() SAXException error", e);
        }
        if (sheets == null) {
            return null;
        }
        while (sheets.hasNext()) {
            curRow = 0;
            sheetIndex++;
            InputStream sheet = null;
            sheet = sheets.next();
            InputSource sheetSource = new InputSource(sheet);
            try {
                parser.parse(sheetSource);
            } catch (IOException e) {
                LOGGER.error("process() IO error", e);
            } catch (SAXException e) {
                LOGGER.error("process() SAX error", e);
            } finally {
                if (sheet != null) {
                    try {
                        sheet.close();
                    } catch (IOException e) {
                        LOGGER.error("process() InputStream close error", e);
                    }
                }
            }

        }
        return result;
    }

    public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
        XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
        this.sst = sst;
        parser.setContentHandler(this);
        return parser;
    }

    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {

        // c => 单元格
        if ("c".equals(name)) {
            // 如果下一个元素是 SST 的索引，则将nextIsString标记为true
            String cellType = attributes.getValue("t");
            if ("s".equals(cellType)) {
                nextIsString = true;
                cellNull = false;
            } else {
                nextIsString = false;
                cellNull = true;
            }
        }
        // 置空
        lastContents = "";
    }

    public void endElement(String uri, String localName, String name) throws SAXException {
        // 根据SST的索引值的到单元格的真正要存储的字符串
        // 这时characters()方法可能会被调用多次
        if (nextIsString) {
            try {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
            } catch (Exception e) {
                //LOGGER.error("endElement() error", e);
            }
        }

        if ("v".equals(name) || "t".equals(name)) {
            String value = lastContents.trim();
            value = "".equals(value) ? " " : value;
            rowlist.add(curCol, value);
            curCol++;
            cellNull = false;
        } else if ("c".equals(name) && cellNull == true) {
            rowlist.add(curCol, "");
            curCol++;
            cellNull = false;
        } else {
            // 如果标签名称为 row ，这说明已到行尾，调用 optRows() 方法
            if ("row".equals(name)) {
                optRows(sheetIndex, curRow, rowlist);
                rowlist.clear();
                totalRow++;
                curRow++;
                curCol = 0;
            }
        }

    }

    public void optRows(int sheetIndex, int curRow, List<String> rowList) {
        Map<String, Object> map = new HashMap<>();
        if (!terminateParseFlag && controlParseNum != -1) {
            if (sheetIndex == 0 && curRow == 0) {
                for (String string : rowlist) {
                    title.add(string);
                }
            } else if (curRow != 0) {
                if (rowlist.size() == title.size()) {
                    for (int i = 0; i < rowlist.size(); i++) {
                        String value=rowlist.get(i);
                        map.put(title.get(i), value);
                    }
                    result.add(map);
                } else {
                    LOGGER.debug("第" + (sheetIndex + 1) + "页，第" + (curRow + 1) + "行数据与第一行数据长度不匹配！");
                }
            }

        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        // 得到单元格内容的值
        lastContents += new String(ch, start, length);
    }
}